<template>
	<div class="add-question">
		<nav-header>
			<template slot="menuBefore">
				<li><router-link to="/portal/help/common-problem" tag="a">常见问题管理</router-link></li>
				<li class="gap">&gt;</li>
			</template>
				<li>{{editFlag === true ? '编辑问题' : '添加问题'}}</li>
		</nav-header>
		<div style="margin-top: 10px"
			v-loading="loading.status"
		    :element-loading-text="loading.txt"
		>
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
				<el-form-item label="问题类型" prop="type_id" class="question-select">
					<div style="width: 220px">
					    <el-select v-model="ruleForm.type_id" filterable placeholder="请选择问题类型">
					      	<el-option
						      v-for="item in problemTypeData"
						      :key="item.id"
						      :label="item.name"
						      :value="item.id">
						    </el-option>
					    </el-select>
				    </div>
				  
				</el-form-item>
				<el-form-item label="问题标题" prop="title">
				    <el-input style="width:580px;"
				    	v-model="ruleForm.title" 
				    	placeholder="请输入20个字以内" 
				    	:maxlength="parseInt(20)"
		      			autocomplete="off"
				    	clearable></el-input>
				</el-form-item>
				<el-form-item label="内容" prop="content">
				    <tinymce 
                        id="d1" 
                        ref="tm" 
                        :plugins="plugins" 
                        :other_options="options" 
                        :toolbar1="toolbar1" 
                        :toolbar2="toolbar2" 
                        v-model="ruleForm.content" 
                        @editorInit="editorInit">
                    </tinymce>
					<div class="tinymce-num"><i>{{tinymceNum}}</i> / 10000</div>
				</el-form-item>
				<el-form-item>
				    <el-button size="medium" @click="cancel()">取消</el-button>					
				    <el-button size="medium" type="primary" @click="submitForm('ruleForm')">保存</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 添加类型 -->
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="添加类型" :visible.sync="AddType" class="addType" width="400px">
			<el-form :model="addForm" :rules="rules" ref="addForm" status-icon label-position="left" label-width="80px">
			    <el-form-item label="类型名称" prop="name">
			      	<el-input 
			      		v-model="addForm.name" 
			      		placeholder="请输入6个字以内" 
			      		autocomplete="off"
			      		:maxlength="parseInt(6)"
			      		clearable
			      		></el-input>
			    </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
			    <el-button @click="AddType = false">取消</el-button>
			    <el-button type="primary" @click="submitForm1('addForm')">确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import axios from '../../../tools/axios' 
	import tinymce from 'vue-tinymce-editor'
  	export default {
	    data() {
	      	return {
	      		loading:{
					status:false,
					txt:'获取数据...',
                },
                tinymceNum: 0, // 编辑器初始长度
	      		problemTypeData:[],
	      		AddType: false,
	      		addForm: {
		            name: '',
		        },
		        ruleForm: {
		        	type_id: '',
		            title: '',
		            content: '',
		        },
		        rules: {
		            title: [
			            { required: true, validator: this.validateTitleName, trigger: 'blur' },
		            ],
		            type_id: [
		            	{ required: true, validator: this.validateContentType, trigger: 'change' }
		            ],
		            content: [
		            	{ required: true, validator: this.validateContent, trigger: 'blur' }
		            ],
		            name: [
			            { required: true, validator: this.validateType, trigger: 'blur' },
		            ],
		        },
		        plugins:['paste','fullscreen','link' ,'image'],
				toolbar1: 'paste,fullscreen,link,image',
				toolbar2: 'table |insertfile undo redo | formatselect  | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | link | image | removeformat',
				options:{
					images_upload_handler:this.images_upload_handler,
	                language_url: '/static/tinymce_languages/zh_CN.js',
	                images_upload_url:this.BASE_URL+'/api/resource/res_upload_permanent',
	                paste_data_images: true,                  // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
	                paste_convert_word_fake_lists: false,     // 插入word文档需要该属性
					paste_webkit_styles: 'all',
					paste_merge_formats: true,
					nonbreaking_force_tab: false,
                    paste_auto_cleanup_on_paste: false,
                    convert_urls: false,
                    // selector: 'textarea',  // change this value according to your HTML
                    // fontsize_formats: '12px 13px 14px 16px 18px 24px 32px 48px', // 字体大小，有些标题给给出的大小不匹配，还是会显示 pt
                    font_formats: `
                        微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                        宋体='宋体',Helvetica,Arial,sans-serif;
                        仿宋='仿宋',Helvetica,Arial,sans-serif;
                        楷体='楷体',Helvetica,Arial,sans-serif;
                        黑体='黑体',Helvetica,Arial,sans-serif;
                        幼圆='幼圆',Helvetica,Arial,sans-serif;
                        隶书='隶书',Helvetica,Arial,sans-serif;
                        华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                        苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                        Arial='Arial',Helvetica,Arial,sans-serif;
                        Verdana=verdana,geneva;
                        Webdings=webdings
                    `,
                    // font_formats: `
                    //     微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;
                    //     宋体='宋体',Helvetica,Arial,sans-serif;
                    //     仿宋='仿宋',Helvetica,Arial,sans-serif;
                    //     仿宋GB2312='仿宋GB2312',Helvetica,Arial,sans-serif;
                    //     楷体='楷体',Helvetica,Arial,sans-serif;
                    //     黑体='黑体',Helvetica,Arial,sans-serif;
                    //     华文新魏='华文新魏',Helvetica,Arial,sans-serif;
                    //     隶书='隶书',Helvetica,Arial,sans-serif;
                    //     苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;
                    //     幼圆='幼圆';
                    //     Arial='Arial',Helvetica,Arial,sans-serif;
                    //     Arial Black=arial black,avant garde;
                    //     Andale Mono=andale mono,times;
                    //     Book Antiqua=book antiqua,palatino;
                    //     Comic Sans MS=comic sans ms,sans-serif;
                    //     Courier New=courier new,courier;
                    //     Georgia=georgia,palatino;
                    //     Impact=impact,chicago;
                    //     Symbol=symbol;
                    //     Simsun='Simsun';
                    //     Tahoma=tahoma,arial,helvetica,sans-serif;
                    //     Terminal=terminal,monaco;
                    //     Trebuchet MS=trebuchet ms,geneva;
                    //     Times New Roman='Times New Roman',Helvetica,Arial,sans-serif;
                    //     Verdana=verdana,geneva;
                    //     Webdings=webdings;
                    //     Wingdings=wingdings,zapf dingbats
                    // `,
	            },
	            editFlag: this.$route.params.id ? true : false,
	      	};
	    },
	    created(){
			this.getProblemType();
			/*************************************TODO******/
			if( this.$route.params.id > 0  ){
				this.loading.status = true;
				setTimeout(()=>{
					this.getProblemInfo();
				},500)
	    		
			}
	    },	
	    watch:{
	    	AddType(){
	    		if(this.AddType === false) {
	    			this.$refs.addForm.resetFields()
	    		}
            },
            /**
             * 监听富文本的内容长度，判断是否超出规定内容
             */
            'ruleForm.content'(newVal, oldVal) {
                setTimeout(() => {
                    let body = document.getElementById('d1_ifr').contentWindow.document.getElementsByTagName('body')[0].textContent;
                    let newLen = body.replace(/\s/g, '').length;
                    let oldLen = this.tinymceNum;

                    // 判断邮件长度是否超过 10000
                    if (newLen > 10000) {
                        this.$message.warning('内容最大长度不可以超过 10000 个字');
                        this.tinymceNum = oldLen;
                        this.ruleForm.content = oldVal;
                    } else {
                        this.tinymceNum = newLen;
                    }
                }, 300);
            }
	    },
	    methods: {
            /**
             * 编辑器初始化
             */
            editorInit() {
                // 修改输入框内文字与边界的宽
                let dom = document.getElementById('d1_ifr').contentWindow.document.getElementById('tinymce');
                dom.style.margin = "8px 25px 45px";
            },
	    	getProblemInfo(){
				// 重写成功回调
				let success = ( data => {
					this.loading.status = false;
					this.ruleForm.id = data.data.id;
					this.ruleForm.type_id = data.data.type_id;
		           	this.ruleForm.title = data.data.title;
		            this.ruleForm.content = data.data.content;
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
				})
  				this.$ajax.get('api/setting/problem',{params:{id:this.$route.params.id},func:{success:success,fail:fail}})
	    	},
	    	// 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
			images_upload_handler (blobInfo, success, failure) {
				if( blobInfo.blob().type.indexOf('image/')  === -1 ){
					failure('只允许上传图片格式的文件')
				}else if( blobInfo.blob().size >  10240000 ) {
			     	failure('图片大小不能超过10M')
			   }else{
					let formData = new FormData();
			            formData.append( 'file', blobInfo.blob() , blobInfo.filename() );
				    let succ = ( data => {
                        // data.data =  data.data.data;
			    		success(this.BASE_URL + data.data.data.file_path)
					});
					let fail = ( data => {
                        // data.data =  data.data.data;
			    		failure(data.data.data.message)
					});
					//******************************TODO 不知为何要重新create*****************//
					const instance = axios.create({
						headers:{
							Authorization:`Bearer ${this.$g.access_token}`,
							DecisionPlatform :` ${this.$g.access_token}`,
							token : sessionStorage.getItem('token'),
						},
			          	withCredentials: true,
			         }) 
				    instance.post('api/resource/res_upload_permanent',formData).then( succ ).catch(fail)
				}
			  
			 
			   
			},
	    	// 关闭
			cancel(){
				this.$router.go(-1)
			},
	    	getProblemType(){
		    	// 重写成功回调
				let success = ( data => {
					this.problemTypeData = data.data;
				});
  				this.$ajax.get('api/setting/problem_type',{params:{},func:{success:success}})
		    	
		    },
		    addProblem(){
		    	let success = ( data => {
					this.$message.success(data.msg);
					this.$router.push('/portal/help/common-problem')
				});
  				this.$ajax.post('api/setting/problem',this.ruleForm,{func:{success:success}})
		    },
		    addProblemType(){
		    	let success = ( data => {
					this.$message.success(data.msg);
					this.AddType = false;
					this.addForm.name = '';
					this.getProblemType();
				});
  				this.$ajax.post('api/setting/problem_type',this.addForm,{func:{success:success}})
		    },
	    	//验证
			validateTitleName(rule, value, callback){
				if (value === '') {
                  	return callback(new Error('请输入问题标题'));
                }  else {
                	callback()
                }
			},
			validateType(rule, value, callback){
				if (value === '') {
                  	return callback(new Error('请输入类型名称'));
                }  else {
                	callback()
                }
			},
			validateContent(rule, value, callback){
				if (value === '') {
                  	return callback(new Error('请输入内容'));
                }else {
                	callback()
                }
			},
			validateContentType(rule, value, callback){
				if (!isEmpty(value)){
                	return callback(new Error('请选择选项'));
                } else {
                	callback()
                }
			},
	      	submitForm(formName) {
		        this.$refs[formName].validate((valid) => {
		          	if (valid) {
		            	this.addProblem();
		          	} else {
		            	return false;
		          	}
		        });
	      	},
	      	submitForm1(formName) {
		        this.$refs[formName].validate((valid) => {
		          	if (valid) {
		            	this.addProblemType();
		          	} else {
		            	return false;
		          	}
		        });
	      	},

	    } ,
	    components:{
			tinymce,
		}
  	}
</script>
<style lang="scss">
	.add-question {
		.question-button {
			text-align: center;

			button {
				min-width: 100px;
			}

			a {
				margin-left: 10px;
			}
		}

		.question-select {
			.el-form-item__content {
				>div {
					display: inline-block;
				}
			}
		}

        #d1_ifr {
            height: 450px !important;
        }

        .tinymce-num {
            position: absolute;
            right: 0;
            bottom: 1px;
            display: block;
            padding-right: 35px;
            width: calc(100% - 1px);
            text-align: right;
            font-size: 12px;
            color: #999;
            background: #F9F9F9;
            box-sizing: border-box;
        }

        .mce-statusbar.mce-container.mce-panel.mce-stack-layout-item.mce-last {
            display: none;
        }

        .mce-tinymce.mce-container.mce-panel[role=application] >div >div:first-child >div >div:first-child   {
            display: none;
        }

        .mce-tinymce.mce-container.mce-panel[role=application] >div >div:first-child >div >div:last-child >div >div:first-child {
            display: none;
        }
	}
</style>